<template>
  <el-form :model="value" ref="value" label-width="100px" class="demo-dynamic">
    <el-form-item
      v-for="(i, index) in value.data"
      :key="i.key"
      :prop="'data.' + index + '.value'"
      :rules="{
      required: true, message: '不能为空', trigger: 'blur'
    }"
    >
      <el-form-item label="名称">
        <el-input v-model="i.name"></el-input>
      </el-form-item>

      <el-form-item label="可选参数">
        <el-tag
          :key="tag"
          v-for="tag in i.options"
          closable
          :disable-transitions="false"
          @close="handleClose(i.options, tag)">
          {{ tag }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible && curIndex === index"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm(index, i.options)"
          @blur="handleInputConfirm(index, i.options)"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput(index)">+ New</el-button>
      </el-form-item>

      <el-form-item label="参数可选数量">
        <el-input-number v-model="i.selectCount" :min="1" :max="10"></el-input-number>
      </el-form-item>

      <el-form-item>
        <el-button @click.prevent="handleRemove(i)">删除</el-button>
      </el-form-item>
    </el-form-item>

    <el-form-item>
      <el-button @click="handleAdd">新增</el-button>
    </el-form-item>

  </el-form>
</template>
<script>
export default {
  props: {
    value: {
      required: true,
      default: {
        data: [{
          name: '',
          options: [],
          selectCount: 1
        }]
      }
    }
  },
  data () {
    return {
      inputVisible: false,
      inputValue: '',
      curIndex: 0
    }
  },
  methods: {
    handleSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          return false
        }
      })
    },
    handleRemove (item) {
      const index = this.value.data.indexOf(item)
      if (index !== -1) {
        this.value.data.splice(index, 1)
      }
    },
    handleAdd () {
      this.value.data.push({
        name: '',
        options: [],
        selectCount: 1
      })
    },
    handleClose (options, tag) {
      options.splice(options.indexOf(tag), 1)
    },

    showInput (index) {
      this.curIndex = index
      this.inputVisible = true
    },

    handleInputConfirm (index, options) {
      const inputValue = this.inputValue
      if (inputValue) {
        options.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin: 10px;
  vertical-align: bottom;
}
</style>
